/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { spawnSync, SpawnSyncOptionsWithBufferEncoding } from 'child_process';
import fs from 'fs';
import fse from 'fs-extra';
import * as path from 'path';

import { DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME, HVIGOR, NPM_TOOL } from '../common/const/const.js';
import { parseJsonFile } from '../common/util/parse-json/parse-json-util';

import { readProjectHvigorConfig } from './hvigor-installer';
import { logFormatedErrorAndExit } from './log.js';
import { HVIGOR_USER_HOME } from './wapper-path-const';

export const BASE_NODE_VERSION = '16.0.0';
const HVIGOR_DEPENDENCY_USE_NPM = 'hvigor.dependency.useNpm';

/**
 * 通过node原生require.resolve接口方法来判断在指定的paths路径中是否可以找到对应的npm包
 *
 * @param {string} packName npm pack name
 * @param {string[]} nodePaths node paths
 * @returns {boolean} true/false
 */
export function hasNpmPackInPaths(packName: string, nodePaths: string[]): boolean {
  try {
    require.resolve(packName, { paths: [...nodePaths] });
    return true;
  } catch (e) {
    return false;
  }
}

/**
 * 获取执行当前脚本的node路径中的npm
 *
 * @returns {string}
 */
export function getNpmPath(): string {
  const nodePath = process.execPath;

  return path.join(path.dirname(nodePath), NPM_TOOL);
}

/**
 * 同步执行命令
 *
 * @param {string} command 命令
 * @param {string[]} parameters 命令参数
 * @param {SpawnSyncOptionsWithBufferEncoding} options 执行配置
 */
export function executeCommand(command: string, parameters: string[], options: SpawnSyncOptionsWithBufferEncoding) {
  const executeResult = spawnSync(command, parameters, options);
  if (executeResult.status !== 0) {
    logFormatedErrorAndExit('00308002', `${command} ${parameters} execute failed.`, ['See above for details.']);
  }
}

/**
 * 离线插件包相对路径转换
 *
 * @param {string} basePath 工程路径
 * @param {string} versionOrPath 离线安装包路径，若是版本号则不进行转换
 */
export function offlinePluginConversion(basePath: string, versionOrPath: string) {
  if (!versionOrPath.startsWith('file:') && !versionOrPath.endsWith('.tgz')) {
    return versionOrPath;
  }
  return path.resolve(basePath, HVIGOR, versionOrPath.replace('file:', ''));
}

/**
 * 判断文件是否存在
 *
 * @param {string} path 文件路径
 * @return {boolean} true/false
 */
export function isFileExists(path: string): boolean {
  return fs.existsSync(path) && fs.statSync(path).isFile();
}

/**
 * 判断是否使用hvigor.dependency.useNpm
 */
export function isHvigorDependencyUseNpm(): boolean {
  const workspaceHvigorConfigJsonPath = path.resolve(HVIGOR_USER_HOME, DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME);
  let workspaceHvigorConfigJsonObj;
  if (fse.existsSync(workspaceHvigorConfigJsonPath)) {
    workspaceHvigorConfigJsonObj = parseJsonFile(workspaceHvigorConfigJsonPath);
  }
  const hvigorConfigProperties = readProjectHvigorConfig()?.properties ?? workspaceHvigorConfigJsonObj?.properties ?? undefined;
  if (hvigorConfigProperties && hvigorConfigProperties[HVIGOR_DEPENDENCY_USE_NPM]) {
    return hvigorConfigProperties[HVIGOR_DEPENDENCY_USE_NPM];
  }
  return false;
}
